﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.Windows.Media.Animation;
using System.Diagnostics;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for StartingPage.xaml
    /// </summary>
    public partial class StartingPage : Window
    {
        ConnectionWindow connectionWindow;
        ServiceController.ServiceController serviceController;
        List<Entities.HostedService> HostedServiceList;
        //List<Entities.Storage_Account.StorageAccount> StorageAccountList;
        bool IsProductionPropertyComplete;
        bool IsStagingPropertyComplete;

        Entities.HostedServiceProperty ServiceProperty;
        //Entities.Storage_Account.StorageAccountProperty AccountProperty;
        Entities.DeploymentProperty StagingDeploymentProperty;
        Entities.DeploymentProperty ProductionDeploymentProperty;
        DeploymentPropertyWindow dpWindow;
        HostServiceProperty1 hsp1;
        String ServiceName;
        private Storyboard startbusy;
        private Storyboard stopbusy;

        public StartingPage()
        {
            InitializeComponent();
            
            HostedServiceList = new List<Entities.HostedService>();
            ServiceProperty = new Entities.HostedServiceProperty();
            serviceController = new ServiceController.ServiceController();
            serviceController.GetListHostServiceCompleted += new ServiceController.ServiceControllerEventHandler(serviceController_GetListHostServiceCompleted);
            //serviceController.GetStorageAccountListCompleted += new ServiceController.ServiceControllerEventHandler(serviceController_GetStorageAccountListCompleted);
            serviceController.GetHostServicePropertyCompleted += new ServiceController.ServiceControllerEventHandler(serviceController_GetHostServicePropertyCompleted);
            //serviceController.GetStorageAccountPropertyCompleted += new ServiceController.ServiceControllerEventHandler(serviceController_GetStorageAccountPropertyCompleted);
            serviceController.GetDeploymentPropertyComplete += new ServiceController.ServiceControllerEventHandler(serviceController_GetDeploymentPropertyComplete);
            ServiceName = String.Empty;
            this.Loaded += new RoutedEventHandler(StartingPage_Loaded);

            startbusy = (Storyboard)this.FindResource("StartBusy");
            stopbusy = (Storyboard)this.FindResource("StopBusy");
        }

        void serviceController_GetDeploymentPropertyComplete(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                MainGrid.Children.Remove(hsp1);
                MainGrid.Children.Remove(dpWindow);
                HideMask();
                if (e.error != null)
                {
                    MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    if (e.DeploymentProperty.DeploymentSlot.Equals("Staging"))
                    {
                        IsStagingPropertyComplete = true;
                        StagingDeploymentProperty = e.DeploymentProperty;
                    }
                    else
                    {
                        IsProductionPropertyComplete = true;
                        ProductionDeploymentProperty = e.DeploymentProperty;
                    }

                    if (IsProductionPropertyComplete && IsStagingPropertyComplete)
                    {
                        IsStagingPropertyComplete = false;
                        IsProductionPropertyComplete = false;

                        dpWindow = new DeploymentPropertyWindow(ProductionDeploymentProperty, StagingDeploymentProperty, ServiceName);


                        dpWindow.SetValue(Grid.RowProperty, 1);
                        dpWindow.SetValue(Grid.ColumnProperty, 1);
                        MainGrid.Children.Add(dpWindow);


                    }
                }
            }));
        }
        

        void serviceController_GetStorageAccountPropertyCompleted(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                HideMask();
                if (e.error != null)
                {
                    MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    //AccountProperty = e.StorageAccountProperty;
                    //StorageAccountProperty Sap = new StorageAccountProperty(AccountProperty);
                    //Sap.SetValue(Grid.RowProperty, 1);
                    //Sap.SetValue(Grid.ColumnProperty, 1);
                    //MainGrid.Children.Add(Sap);


                }
            }));





        }

        //void serviceController_GetStorageAccountListCompleted(object sender, ServiceController.ServiceControllerEventArgs e)
        //{


        //    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
        //    {
        //        HideMask();
        //        if (e.error != null)
        //        {
        //            MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        //        }
        //        else
        //        {
        //            StorageAccountList = e.StorageAccountList;
        //            SetTreeView(StorageAccountList);
        //        }


        //    }));




            
        //}

        //private void SetTreeView(List<Entities.Storage_Account.StorageAccount> StorageAccountList)
        //{
        //    foreach (var item in StorageAccountList)
        //    {

        //        StorageAccountContextMenu AccountContextMenu = new StorageAccountContextMenu(item.ServiceName, serviceController);


        //        TreeViewItem ServiceNode = new TreeViewItem()
        //        {
        //            Header = item.ServiceName,
        //            ContextMenu = AccountContextMenu.Header.ContextMenu,
        //            IsExpanded = true


        //        };

                
        //        App.StorageAccountList.Add(new Entities.Storage_Account.StorageAccount()
        //        {
        //            ServiceName = item.ServiceName,
        //            Url = item.Url

        //        });

        //        //TreeViewStorageServices.Items.Add(ServiceNode);
             





        //    }
        //}

       

        void serviceController_GetHostServicePropertyCompleted(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                HideMask();
                MainGrid.Children.Remove(hsp1);
                MainGrid.Children.Remove(dpWindow);
                if (e.error != null)
                {
                    MessageBox.Show(e.error.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {

                    ServiceProperty = e.HostServiceProperty;
                    hsp1 = new HostServiceProperty1(ServiceProperty);
                    hsp1.SetValue(Grid.RowProperty, 1);
                    hsp1.SetValue(Grid.ColumnProperty, 1);
                    MainGrid.Children.Add(hsp1);

                    
                }
            }));

        }

        void serviceController_GetListHostServiceCompleted(object sender, ServiceController.ServiceControllerEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
                {
                    HideMask();
                    if (e.error != null)
                {
                    MessageBox.Show(e.error.Message,"Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    HostedServiceList = e.ListHostService;
                    SetTreeView(HostedServiceList);
                    ButtonConnect.Content = "Disconnect";

                }


                }));
            
        }

        private void SetTreeView(List<Entities.HostedService> List)
        {
            foreach (var item in List)
            {


                //HostServiceContextMenu ContextMenu = new HostServiceContextMenu(item.ServiceName, serviceController);
                //{
                //    //ParentPage = this,
                //    //DataContext = newTable,
                //    //IsNewTableMenuEnabled = !((Cerebrata.CloudStorage.Azure.Entities.Common.StorageAccountInformation)(ParentRadTreeViewItem).DataContext).IsDevFabricConnection,
                //    //IsEditTableMenuEnabled = !((Cerebrata.CloudStorage.Azure.Entities.Common.StorageAccountInformation)(ParentRadTreeViewItem).DataContext).IsDevFabricConnection,
                //};


                TreeViewItem tvi = tvi = new TreeViewItem();
                tvi.Header = item.ServiceName;

                TreeViewItem ServiceProperty = new TreeViewItem();
                ServiceProperty.Header = "Service Properties";
                ServiceProperty.MouseLeftButtonUp += new MouseButtonEventHandler(ServiceProperty_MouseLeftButtonUp);
                tvi.Items.Add(ServiceProperty);

                TreeViewItem DeploymentProperty = new TreeViewItem();
                DeploymentProperty.Header = "Deployment Properties";
                DeploymentProperty.MouseLeftButtonUp += new MouseButtonEventHandler(DeploymentProperty_MouseLeftButtonUp);
                tvi.Items.Add(DeploymentProperty);

                //TreeViewItem tvi = this.FindResource("TreeViewServiceItemResource") as TreeViewItem;
                //tvi.Header = item.ServiceName;
               
               
                App.HostedServiceList.Add(new Entities.HostedService() { ServiceName=item.ServiceName, Url=item.Url });

                TreeViewHostService.Items.Add(tvi);
               

            }
        }

        void StartingPage_Loaded(object sender, RoutedEventArgs e)
        {
            IsProductionPropertyComplete = false;
            IsStagingPropertyComplete = false;

            connectionWindow = new ConnectionWindow(serviceController);
            connectionWindow.Owner = this;
            if (connectionWindow.ShowDialog() == true)
            {
                ShowMask();
            }
        }
        private void ButtonConnect_Click(object sender, RoutedEventArgs e)
        {
            if (ButtonConnect.Content.Equals("Disconnect"))
            {
                if (MessageBox.Show("Are you sure you want to disconnect ?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    TreeViewHostService.Items.Clear();
                    ButtonConnect.Content = "Connect";
                    //TextBoxSubscriptionID.Text = "";
                    MainGrid.Children.Remove(hsp1);
                    MainGrid.Children.Remove(dpWindow);
                }

            }
            else
            {
                connectionWindow = new ConnectionWindow(serviceController);
                connectionWindow.Owner = this;
                if (connectionWindow.ShowDialog() == true)
                {
                    ShowMask();
                }
            }
        }

        

        //private void TreeViewHostService_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        //{
        //    MessageBox.Show("Click call");
        //}
        
        private void ServiceProperty_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            TreeViewItem tvi = sender as TreeViewItem;
            TreeViewItem t = (TreeViewItem)tvi.Parent;
            if (t != null)
            {
                ShowMask();
                serviceController.GetHostServicePropertyAsync(App.SubscriptionID, App.CertificatePath, t.Header.ToString(), true,null);
            }
            
            
            
        }

        private void DeploymentProperty_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem tvi = sender as TreeViewItem;
            TreeViewItem t = (TreeViewItem)tvi.Parent;
            ServiceName = t.Header.ToString();

            if (t != null)
            {
                MainGrid.Children.Remove(hsp1);
                MainGrid.Children.Remove(dpWindow);
                dpWindow = new DeploymentPropertyWindow(ServiceName);
                dpWindow.SetValue(Grid.RowProperty, 1);
                dpWindow.SetValue(Grid.ColumnProperty, 1);
                MainGrid.Children.Add(dpWindow);
                //serviceController.GetDeploymentPropertyAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Production",null);
                //serviceController.GetDeploymentPropertyAsync(App.SubscriptionID, App.CertificatePath, ServiceName, "Staging",null);
                
            }
        }

        private void HideMask()
        {
            startbusy.Stop();
            stopbusy.Begin();
            border2_Copy.Visibility = Visibility.Collapsed;
        }

        private void ShowMask()
        {
            border2_Copy.Visibility = Visibility.Visible;
            startbusy.Begin();
        }

        private void ButtonAboutUs_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("www.cerebrata.com/?r=ashm");
        }

        private void ButtonHelp_Click(object sender, RoutedEventArgs e)
        {
            Process.Start("http://www.cerebrata.com/Docs/AzureHostedServicesManager.UserGuide.pdf");
        }

        
    }
}
